package com.atguigu.spzx.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.atguigu.spzx.cart.service.CartService;
import com.atguigu.spzx.exception.GuiguException;
import com.atguigu.spzx.feign.product.ProductFeignClient;
import com.atguigu.spzx.model.entity.h5.CartInfo;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.utils.AuthContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ProductFeignClient productFeignClient;

    private String getCartKey(Long userId) {
        //定义key user:cart:userId
        return "user:cart:" + userId;
    }

    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        Long id = AuthContextUtil.getUserInfo().getId();
        String key = getCartKey(id);

        Object skuInfo = redisTemplate.opsForHash().get(key, String.valueOf(skuId));
        CartInfo cartInfo = null;
        if (skuInfo != null) {
            cartInfo = JSON.parseObject(skuInfo.toString(), CartInfo.class);
            cartInfo.setSkuNum(cartInfo.getSkuNum() + skuNum);
            cartInfo.setIsChecked(1);
            cartInfo.setUpdateTime(new Date());
        } else {
            cartInfo = new CartInfo();
            ProductSku productSku = productFeignClient.getBySkuId(skuId);
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuNum(skuNum);
            cartInfo.setSkuId(skuId);
            cartInfo.setUserId(id);
            cartInfo.setImgUrl(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setIsChecked(1);
            cartInfo.setCreateTime(new Date());
            cartInfo.setUpdateTime(new Date());
        }
        redisTemplate.opsForHash().put(key, String.valueOf(skuId), JSON.toJSONString(cartInfo));

    }

    @Override
    public List<CartInfo> getCartList() {
        String key = getCartKey(AuthContextUtil.getUserInfo().getId());
        List<Object> cartInfoList = redisTemplate.opsForHash().values(key);
        if (!CollectionUtils.isEmpty(cartInfoList)) {
            List<CartInfo> infoList = cartInfoList.stream().map(cartInfoJSON -> JSON.parseObject(cartInfoJSON.toString(), CartInfo.class))
                    .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                    .collect(Collectors.toList());
            return infoList;
        }
        return new ArrayList<>();
    }

    @Override
    public void deleteCart(Long skuId) {
        String key = getCartKey(AuthContextUtil.getUserInfo().getId());
        redisTemplate.opsForHash().delete(key, String.valueOf(skuId));
    }

    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        String key = getCartKey(AuthContextUtil.getUserInfo().getId());
        Boolean hasKey = redisTemplate.opsForHash().hasKey(key, String.valueOf(skuId));
        if (hasKey) {
            Object skuInfo = redisTemplate.opsForHash().get(key, String.valueOf(skuId));
            CartInfo cartInfo = JSON.parseObject(skuInfo.toString(), CartInfo.class);
            cartInfo.setIsChecked(isChecked);
            cartInfo.setUpdateTime(new Date());
            redisTemplate.opsForHash().put(key, String.valueOf(skuId), JSON.toJSONString(cartInfo));
        }
    }

    @Override
    public void clearCart() {
        String key = getCartKey(AuthContextUtil.getUserInfo().getId());
        redisTemplate.opsForHash().delete(key);
    }

    @Override
    public void allCheckCart(Integer isChecked) {
        String key = getCartKey(AuthContextUtil.getUserInfo().getId());
        List<Object> values = redisTemplate.opsForHash().values(key);
        if (!CollectionUtils.isEmpty(values)) {
            for (Object value : values) {
                CartInfo cartInfo = JSON.parseObject(value.toString(), CartInfo.class);
                Long skuId = cartInfo.getSkuId();
                cartInfo.setIsChecked(isChecked);
                cartInfo.setUpdateTime(new Date());
                redisTemplate.opsForHash().put(key, String.valueOf(skuId), JSON.toJSONString(cartInfo));
            }
        }

    }


    @Override
    public List<CartInfo> getAllCkecked() {
        Long userId = AuthContextUtil.getUserInfo().getId();
        String cartKey = getCartKey(userId);
        List<Object> objectList = redisTemplate.opsForHash().values(cartKey);       // 获取所有的购物项数据
        if(!CollectionUtils.isEmpty(objectList)) {
            List<CartInfo> cartInfoList = objectList.stream().map(cartInfoJSON -> JSON.parseObject(cartInfoJSON.toString(), CartInfo.class))
                    .filter(cartInfo -> cartInfo.getIsChecked() == 1)
                    .collect(Collectors.toList());
            return cartInfoList ;
        }
        return new ArrayList<>() ;
    }

    @Override
    public void deleteChecked() {

        Long userId = AuthContextUtil.getUserInfo().getId();
        String cartKey = getCartKey(userId);
        List<Object> objectList = redisTemplate.opsForHash().values(cartKey);
        if(!CollectionUtils.isEmpty(objectList)) {
            if(!CollectionUtils.isEmpty(objectList)) {
                objectList.stream().map(cartInfoJSON -> JSON.parseObject(cartInfoJSON.toString(), CartInfo.class))
                        .filter(cartInfo -> cartInfo.getIsChecked() == 1)
                        .forEach(cartInfo -> redisTemplate.opsForHash().delete(cartKey , String.valueOf(cartInfo.getSkuId())));
            }
        }
    }
}
